<script>
// IM相关组件
let WebIM = (wx.WebIM = require('./utils/WebIM')['default']);
let msgStorage = require('./components/chat/msgstorage');
let msgType = require('./components/chat/msgtype');
let disp = require('./utils/broadcast');

import constant from './utils/Constant.js';
import MessageUser from  './utils/MessageUser.js';

// 消息回执
function ack(receiveMsg) {
	// 处理未读消息回执
	var bodyId = receiveMsg.id; // 需要发送已读回执的消息id

	var ackMsg = new WebIM.message('read', WebIM.conn.getUniqueId());
	ackMsg.set({
		id: bodyId,
		to: receiveMsg.from
	});
	WebIM.conn.send(ackMsg.body);
}

function addUser(message){
	let userArr =  uni.getStorageSync(constant.userFriend)||[];
	let userInfo =  uni.getStorageSync(constant.user);
	
	let index = userArr&&userArr.findIndex(user=>{
		return user.userId === message.from
	});
	
	var unRead = 0;
	if(index!==null&&index>-1){
		let messageUser =  userArr[index];
		userArr.splice(index,1);
		unRead = messageUser.unreadCount+1;
	}else{
		unRead = 1;
	}
	let msu = new MessageUser(
		message.from,
		message.ext.nickname,
		message.ext.img,
		message.ext.isVip,
		message.contentsType,
		message.data,
		message.time,
		false,
		unRead
	);
	userArr.unshift(msu);
	uni.setStorage({
		key:constant.userFriend,
		data:userArr
	});
	disp.fire("em.main.unRead");
}

// 错误消息弹框
function onMessageError(err) {
	if (err.type === 'error') {
		uni.showToast({
			title: err.errorText
		});
		return false;
	}
	return true;
}

// 统计未读消息数
function calcUnReadSpot(message) {
	let user = uni.getStorageSync(constant.user);
	uni.getStorageInfo({
		success: function(res) {
			let storageKeys = res.keys;
			let newChatMsgKeys = [];
			let historyChatMsgKeys = [];
			
			storageKeys.forEach(item => {
				if (item.indexOf(user.accountNo) > -1 && item.indexOf('rendered_') == -1) {
					newChatMsgKeys.push(item);
				}
			});
			let count = newChatMsgKeys.reduce(function(result, curMember, idx) {
				let chatMsgs;
				chatMsgs = uni.getStorageSync(curMember) || [];
				return result + chatMsgs.length;
			}, 0);
			getApp().globalData.unReadMessageNum = count;
			disp.fire('em.unreadspot', message);
		}
	});
}


import { mapState, mapMutations } from 'vuex';

export default {
	// 全局数据
	globalData: {
		// 未读消息数
		unReadMessageNum: 0,
		// 聊天用户列表
		saveFriendList: [],
		isIPX: false, //是否为iphone X
		conn: {
			closed: false,
			curOpenOpt: {},

			open(opt) {
				// uni.showLoading({
				// 	title: '正在初始化客户端..',
				// 	mask: true
				// });
				this.curOpenOpt = opt;
				WebIM.conn.open(opt);
				this.closed = false;
			},

			reopen() {
				if (this.closed) {
					WebIM.conn.open(this.curOpenOpt);
					this.closed = false;
				}
			}
		},

		checkIsIPhoneX: function() {
			const me = this;
			uni.getSystemInfo({
				success: function(res) {
					// 根据 model 进行判断
					if (res.model && res.model.search('iPhone X') != -1) {
						me.isIPX = true;
					}
				}
			});
		}
	},

	onLaunch: function() {
		plus.navigator.closeSplashscreen();
		plus.screen.lockOrientation('portrait-primary');
		let user = uni.getStorageSync(constant.user);
		if (!user) {
			uni.navigateTo({
				url: './pages/login/login'
			});
		}else{
			if(user.userSex===null){
				uni.navigateTo({
					url: './pages/user-gender/user-gender'
				});
			}else if (user.userHeight===null){
				uni.navigateTo({
					url: './pages/user-init/user-init'
				});
			}else{
				this.globalData.conn.open({
				  apiUrl: WebIM.config.apiURL,
				  user: user.accountNo,
				  pwd: 'Aa123456',
				  //grant_type: this.data.grant_type,
				  appKey: WebIM.config.appkey
				});
				constant.initCustomer();
			}
		}

		uni.setStorageSync('logs', logs);
		
		
		var me = this;
		var logs = uni.getStorageSync("logs") || [];
		logs.unshift(Date.now());
		uni.setStorageSync("logs", logs); //
		
		disp.on("em.main.unRead", function () {
			var pages = getCurrentPages();
var currPage = pages[pages.length - 1]; //当前页面
		  if(me.globalData.unReadMessageNum>0&&!currPage.route.includes('/chat/chat')){
		  	let text=me.globalData.unReadMessageNum<99&&me.globalData.unReadMessageNum>0?me.globalData.unReadMessageNum:'...'
		  	uni.showTabBarRedDot({
		  		index: 2,
		  		success() {
		  			uni.setTabBarBadge({
		  				index: 2,
		  				text: text+''
		  			});
		  		}
		  	});
		  }
		});
		
		
		
		
		disp.on("em.main.ready", function () {
		  calcUnReadSpot();
		});
		disp.on("em.chatroom.leave", function () {
		  calcUnReadSpot();
		});
		disp.on("em.chat.session.remove", function () {
		  calcUnReadSpot();
		});
		disp.on("em.chat.audio.fileLoaded", function () {
		  calcUnReadSpot();
		});
		disp.on("em.main.deleteFriend", function () {
		  calcUnReadSpot();
		});
		disp.on("em.chat.audio.fileLoaded", function () {
		  calcUnReadSpot();
		});
		
		WebIM.conn.listen({
		  onOpened(message) {
			   uni.hideLoading();
			  console.log('连接成功');
		  },
		
		  onReconnect() {
		    uni.showToast({
		      title: "重连中...",
		      duration: 2000,
		    });
		  },
		  onSocketConnected() {
		    uni.showToast({
		      title: "socket连接成功",
		      duration: 2000,
		    });
		  },
		  onClosed() {
		    uni.showToast({
		      title: "网络已断开",
		      icon: "none",
		      duration: 2000,
		    });
		    me.globalData.conn.closed = true;
		    WebIM.conn.close();
		  },
		  onReadMessage(message) {
		    console.log('已读', message)
		  },
		
		  onRoster(message) {
		  },
		
		  onVideoMessage(message) {
		    console.log("onVideoMessage: ", message);
		
		    if (message) {
		      msgStorage.saveReceiveMsg(message, msgType.VIDEO);
			  me.globalData.unReadMessageNum +=1;
		    }
		    addUser(message);
		    ack(message);
		  },
		
		  onAudioMessage(message) {
		    console.log("onAudioMessage", message);
		
		    if (message) {
		      if (onMessageError(message)) {
				 me.globalData.unReadMessageNum +=1;
		        msgStorage.saveReceiveMsg(message, msgType.AUDIO);
		      }
		      addUser(message);
		      ack(message);
		    }
		  },
		
		  onCmdMessage(message) {
		    console.log("onCmdMessage", message);
		
		    if (message) {
		      if (onMessageError(message)) {
				  me.globalData.unReadMessageNum +=1;
		        msgStorage.saveReceiveMsg(message, msgType.CMD);
		      }
		
		      addUser(message);
		      ack(message);
		    }
		  },
		  onTextMessage(message) {
		    console.log("onTextMessage", message);
		    if (message) {
		      if (onMessageError(message)) {
				  me.globalData.unReadMessageNum +=1;
		        msgStorage.saveReceiveMsg(message, msgType.TEXT);
		      }
		      addUser(message);
		      ack(message);
		    }
		  },
		
		  onEmojiMessage(message) {
		    console.log("onEmojiMessage", message);
		    if (message) {
		      if (onMessageError(message)) {
		        msgStorage.saveReceiveMsg(message, msgType.EMOJI);
				me.globalData.unReadMessageNum +=1;
		      }
		      addUser(message);
		      ack(message);
		    }
		  },
		
		  onPictureMessage(message) {
		    console.log("onPictureMessage", message);
		    if (message) {
		      if (onMessageError(message)) {
		        msgStorage.saveReceiveMsg(message, msgType.IMAGE);
				me.globalData.unReadMessageNum +=1;
		      }
		      addUser(message);
		      ack(message);
		    }
		  },
		
		  onFileMessage(message) {
		    console.log("onFileMessage", message);
		    if (message) {
		      if (onMessageError(message)) {
		        msgStorage.saveReceiveMsg(message, msgType.FILE);
				me.globalData.unReadMessageNum +=1;
		      }
		      addUser(message);
		      ack(message);
		    }
		  },
		
		  // 各种异常
		  onError(error) {
			uni.hideLoading();
		    console.log(error); 
		
		    if (error.type == WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
		      uni.hideLoading();
		      disp.fire("em.error.passwordErr");
		    }
		
		    if (error.type == WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
		      uni.hideLoading();
		      disp.fire("em.error.tokenErr");
		    }
		
		    if (error.type == "socket_error") {
		      ///sendMsgError
		      console.log("socket_errorsocket_error", error);
		      uni.showToast({
		        title: "网络已断开",
		        icon: "none",
		        duration: 2000,
		      });
		      disp.fire("em.error.sendMsgErr", error);
		    }
		  },
		});
		this.globalData.checkIsIPhoneX();
		
	},
	onShow() {
		console.log('App Show');
	},
	onHide: function() {
		console.log('App Hide');
	}
};
</script>

<style>
/* 设计图为375， rpx默认是750,px转rpx公式为750*设计图大小/375 */
/* 公共的css引入 */
/* #ifndef APP-PLUS-NVUE */

@import './common/uni.css';
/* #endif*/

/* 引入自定义图标库 */
/* #ifndef APP-PLUS-NVUE */
@import './common/icon.css';
/* 引入动画库 */
/* #endif*/
</style>
